package cn.itcast.bos.Realm;

import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.PermissionService;
import cn.itcast.bos.service.system.RoleService;
import cn.itcast.bos.service.system.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

//@Component
public class BosRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //授权管理
        System.out.println("授权管理");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //根据当前登陆用户查询对应得权限和角色
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        //调用业务层,查询角色
        List<Role> roles = roleService.findByUser(user);
        for (Role role:roles){
            simpleAuthorizationInfo.addRole(role.getKeyword());
        }
        //调用业务层,查询权限
        List<Permission> permissions =permissionService.findByUser(user);
        for(Permission permission :permissions){
            simpleAuthorizationInfo.addStringPermission(permission.getKeyword());
        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //认证管理
        System.out.println("认证管理");
        //转换token
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        //查询user
        User user = userService.findByUsername(usernamePasswordToken.getUsername());
        if(user ==null){
            return null;
        }else{
            //用户名存在
            //当返回用户密码时,securityManage安全管理器自动比较返回的密码与输入的密码是否一致,
            //如果一致,返回登陆成功,不一致返回密码错误;
            return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        }
    }
}
